package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.MyCollection;
import com.guigu.eduservice.mapper.CollectionMapper;
import com.guigu.eduservice.service.CollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.eduservice.service.EquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 收藏表（存储用户收藏的设备信息） 服务实现类
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, MyCollection> implements CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;
    @Autowired
    private EquipmentService equipmentService;
    @Override
    public List<MyCollection> getAllByUid(long uid) {
        // 1. 入参合法性校验（虽然long基本类型不会为null，但可根据业务补充范围校验）
        if (uid <= 0) {
            // 非法用户ID，返回空列表（或抛出异常，根据业务需求调整）
            return new ArrayList<>();
        }
        LambdaQueryWrapper<MyCollection> myCollectionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        myCollectionLambdaQueryWrapper.eq(MyCollection::getUserId,uid);
        List<MyCollection> myCollections = collectionMapper.selectList(myCollectionLambdaQueryWrapper);
        if (myCollections == null || myCollections.isEmpty()) {
            // 无收藏数据，直接返回空列表（避免后续循环操作）
            return new ArrayList<>();
        }
        for (MyCollection myCollection : myCollections) {
            // 4.1 判断当前收藏对象是否为null（避免单个异常数据影响整体）
            if (myCollection == null) {
                continue;
            }

            // 4.2 判断设备ID是否合法（避免无效ID查询）
            Long equipmentId = myCollection.getEquipmentId();
            if (equipmentId == null || equipmentId <= 0) {
                myCollection.setEquipment(null); // 明确设为null，避免后续处理NPE
                continue;
            }

            // 4.3 查询设备信息（判断service返回是否为null）
            Equipment equipment = equipmentService.getByIdImageV(equipmentId);
            myCollection.setEquipment(equipment); // 允许设备为null（如设备已删除）
        }
        return myCollections;
    }
}
